package com.originskyseed.platform.role.provider;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.originskyseed.platform.common.api.constant.RedisKeyConstans;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.redis.util.RedisUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.role.mapper.MenuMapper;
import com.originskyseed.platform.role.mapper.RoleMapper;
import com.originskyseed.platform.role.mapper.RoleRelMenuMapper;
import com.originskyseed.platform.role.model.Menu;
import com.originskyseed.platform.role.model.Role;
import com.originskyseed.platform.role.model.RoleRelMenu;
import com.originskyseed.platform.role.service.IRoleService;

/**
 * 角色表Service接口实现类（OSI_ROLE）
 *
 * @author LiangMingHui
 */
@DubboService
@Component("roleService")
public class RoleServiceImpl implements IRoleService {

	@Resource
	private RoleMapper roleMapper;

	@Resource
	private RoleRelMenuMapper roleRelMenuMapper;

	@Resource
	private MenuMapper menuMapper;

	/**
	 * 删除记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKey(String id) throws Exception {
		return this.roleMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKeys(List<String> ids) throws Exception {
		if (!(ids.size() > 0)) {
			throw new Exception("数据参数有误！");
		}
		return this.roleMapper.deleteByPrimaryKeys(ids);
	}

	/**
	 * 插入记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insert(Role record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.roleMapper.insert(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(Role record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.roleMapper.insertSelective(record);
	}

	/**
	 * 更新记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKey(Role record) throws Exception {
		record.setUpdateTime(new Date());
		return this.roleMapper.updateByPrimaryKey(record);
	}

	/**
	 * 更新记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelective(Role record) throws Exception {
		record.setUpdateTime(new Date());
		return this.roleMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 置顶接口
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	public int updateIsTop(Role record) throws Exception {
		this.roleMapper.updateIsTop();

		record.setUpdateTime(new Date());
		return this.roleMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 查询记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Role selectByPrimaryKey(String id) throws Exception {
		return this.roleMapper.selectByPrimaryKey(id);
	}


	/**
	 * 根据code查询记录
	 *
	 * @param code
	 * @return
	 * @throws Exception
	 */
	public Role selectByCode(String code) throws Exception{
		return this.roleMapper.selectByRoleCode(code);
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Role> selectList(Role record) throws Exception {
		return this.roleMapper.selectList(record);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Role> selectListByPage(Map<String, Object> params, BasePage<Role> page) throws Exception {
		params.put("page", page);
		List<Role> list = this.roleMapper.selectListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 分页查询列表,关联商城表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Role> selectListJoinMallByPage(Map<String, Object> params, BasePage<Role> page) throws Exception {
		params.put("page", page);
		List<Role> list = this.roleMapper.selectListJoinMallByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 查询全部列表,关联商城表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Role> selectListJoinMall(Map<String, Object> params) throws Exception {
		List<Role> list = this.roleMapper.selectListJoinMall(params);
		return list;
	}

	/**
	 * 是否存在角色代码
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public Boolean existCode(Role record) throws Exception {
		return this.roleMapper.existCode(record);
	}

	/**
	 * 根据用户标识获取角色列表
	 *
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Role> selectByUserId(String userId) throws Exception {
		return this.roleMapper.selectByUserId(userId);
	}

	/**
	 * 查询角色绑定权限树
	 *
	 * @param roleId
	 * @param sysType
	 * @return
	 * @throws Exception
	 */
	@Override
	public JSONArray roleBindPermissionSelect(String roleId, Integer sysType, String mallId) throws Exception {
		JSONArray result = new JSONArray();

		// 获取商城所有权限列表
		Menu queryMenu = new Menu();
		// queryPermission.setSysType(sysType);
		// queryPermission.setStatus(1);
		List<Menu> menuList = this.menuMapper.selectList(queryMenu);
		List<RoleRelMenu> roleRelMenuList = this.roleRelMenuMapper.selectByRoleId(roleId);

		// 追加权限树节点
		for (Menu menu : menuList) {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("id", menu.getId());
			jsonObject.put("pid", menu.getParentId());
			jsonObject.put("name", menu.getName());
			if (menu.getParentId() == null) {
				jsonObject.put("open", true);
			} else {
				jsonObject.put("open", false);
			}
			for (RoleRelMenu roleRelMenu : roleRelMenuList) {
				if (roleRelMenu.getPermissionId().equals(menu.getId())) {
					jsonObject.put("checked", true);
					jsonObject.put("open", true);
					break;
				}
			}
			result.add(jsonObject);
		}
		return result;
	}

	/**
	 * 根据userAccount查询供应商是否存在
	 *
	 * @param userAccount
	 * @return
	 * @throws Exception
	 */
	@Override
	public Integer selectSupplierNameByUserAccount(String userAccount) throws Exception {
		return this.roleMapper.selectSupplierNameByUserAccount(userAccount);
	}

	@Override
	public JSONArray roleBindPermissionSelectList(String roleId, Integer sysType, String mallId) throws Exception {
		Menu queryMenu = new Menu();
		queryMenu.setSysType(sysType);
		queryMenu.setIsShow(1);
		// 全部权限
		List<Menu> menuList = this.menuMapper.selectList(queryMenu);
		List<Menu> parentList = new ArrayList<Menu>();
		// 角色权限关系
		List<RoleRelMenu> roleRelPermissionList = this.roleRelMenuMapper.selectByRoleId(roleId);

		for (Menu menu : parentList) {
			menuList.remove(menu);
		}
		return build2Tree(menuList, parentList, roleRelPermissionList);
	}

	@Override
	public JSONArray roleBindPermissionSelectListAdmin(String roleId, Integer sysType) throws Exception {
		Menu queryMenu = new Menu();
		queryMenu.setSysType(sysType);
		List<Menu> permissionList = this.menuMapper.selectList(queryMenu);
		List<Menu> parentList = new ArrayList<Menu>();
		// 角色权限关系
		List<RoleRelMenu> roleRelMenuList = this.roleRelMenuMapper.selectByRoleId(roleId);

		// 所属平台下的根权限
		for (Menu menu : permissionList) {
			if (menu.getParentId() == null) {
				parentList.add(menu);
			}
		}
		for (Menu menu : parentList) {
			permissionList.remove(menu);
		}
		return build2Tree(permissionList, parentList, roleRelMenuList);
	}

	@Override
	public List<Role> selectByUserIdAndMallId(String userId, String mallId) throws Exception {
		return this.roleMapper.selectByUserIdAndMallId(userId, mallId);
	}

	/**
	 * 清除角色权限缓存
	 */
	public void cleanRolePermissionCache() {
		RedisUtil.getInstance().delete(RedisKeyConstans.ROLE_PERMISSION_RELATION_KEY);
	}

	/**
	 * 批量修改状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateStatusByIds(Map<String, Object> map) throws Exception {
		return this.roleMapper.updateStatusByIds(map);
	}

	/**
	 * 批量修改删除状态
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateIsDelByIds(Map<String, Object> map) throws Exception {
		return this.roleMapper.updateIsDelByIds(map);
	}

	/**
	 * 查询角色编码
	 * 
	 * @return
	 * @throws Exception
	 */
	public String selectRoleCode() throws Exception {
		return this.roleMapper.selectRoleCode();
	}

	/**
	 * 查询最大的优先级
	 * 
	 * @return
	 * @throws Exception
	 */
	public Integer selectPrority() throws Exception {
		return this.roleMapper.selectPrority();
	}

	/**
	 * 根据优先级查询角色
	 * 
	 * @param prority
	 * @return
	 * @throws Exception
	 */
	public Role selectRoleByPrority(Integer prority) throws Exception {
		return this.roleMapper.selectRoleByPrority(prority);
	}

	/**
	 * 更新排序信息
	 *
	 * @param downRole
	 * @param upRole
	 * @return
	 * @throws Exception
	 */
	public int updatePrority(Role downRole, Role upRole) throws Exception {
		downRole.setUpdateTime(new Date());
		upRole.setUpdateTime(new Date());
		this.roleMapper.updateByPrimaryKeySelective(upRole);
		return this.roleMapper.updateByPrimaryKeySelective(downRole);
	}

	/**
	 * 根据优先级查询角色
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public Role selectByPrioritySort(Map<String, Object> map) throws Exception {
		return this.roleMapper.selectByPrioritySort(map);
	}

	/**
	 * 构建树
	 *
	 * @param list       包含所有数据
	 * @param parentList 只包含根节点或父节点数据
	 * @return
	 */
	private JSONArray build2Tree(List<Menu> list, List<Menu> parentList, List<RoleRelMenu> roleRelMenuList) {
		JSONArray ary = new JSONArray();
		if (!list.isEmpty() && !parentList.isEmpty()) {
			JSONObject obj;
			// 移除父节点
			list.removeAll(parentList);
			List<Menu> childList;
			for (Menu menu : parentList) {
				obj = new JSONObject();
				obj.put("id", menu.getId());
				obj.put("pid", menu.getParentId());
				obj.put("name", menu.getName());
				for (RoleRelMenu roleRelMenu : roleRelMenuList) {
					if (roleRelMenu.getPermissionId().equals(menu.getId())) {
						obj.put("checked", true);
						break;
					}
				}
				// 默认选中根节点
				if (StringUtils.isEmpty(menu.getParentId())) {
					obj.put("checked", true);
				}
				// 查找子节点
				childList = findChildren(list, menu);
				if (hasChildren(childList)) {
					obj.put("children", build2Tree(list, childList, roleRelMenuList));
				}
				ary.add(obj);
			}
		}
		return ary;
	}

	/**
	 * 查找当前父节点下的子节点数据
	 *
	 * @param list 去除父节点的所有数据
	 * @param menu 父节点
	 * @return
	 */
	private List<Menu> findChildren(List<Menu> list, Menu menu) {
		List<Menu> childList = new ArrayList<Menu>();
		if (!list.isEmpty()) {
			for (Menu cms : list) {
				if (cms.getParentId().equals(menu.getId())) {
					childList.add(cms);
				}
			}
		}
		return childList;
	}

	private boolean hasChildren(List<Menu> list) {
		return list.size() > 0 ? true : false;
	}
}